package com.xuecheng.order.service.impl;

import cn.hutool.core.util.StrUtil;
import com.xuecheng.commons.constants.OrdersConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.order.config.PayTemplate;
import com.xuecheng.order.domain.Orders;
import com.xuecheng.order.domain.Payment;
import com.xuecheng.order.mapper.PaymentMapper;
import com.xuecheng.order.service.OrdersService;
import com.xuecheng.order.service.PaymentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 订单支付信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-12-13
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements PaymentService {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private PayTemplate payTemplate;
    // 支付二维码
    @Override
    public ResponseResult<String> createPay(String orderNo) {
            // 1.查询订单
        Orders orders = ordersService.lambdaQuery()
                .eq(Orders::getOrderNo, orderNo)
                .one();
        // 2.校验订单状态必须为 未支付   Iteger是包装类  -127~128要用equals
        if (!orders.getStatus().equals(OrdersConstants.ORDER_INIT_STATUS)) {
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
            // 3.查询订单明细
        Payment payment = this.lambdaQuery()
                .eq(Payment::getOrderNo, orderNo)
                .one();
        if (payment != null) {//3-1 查到了，直接返回支付连接
            return ResponseResult.okResult(payment.getPayResponse());
        }else {
            // 3-2 没查到
            // 调用微信工具类生成支付连接 // 教学环境，支付环境写死为1分钱
            String payUrl = payTemplate.createOrder(orders.getOrderNo(), 1L, orders.getCoursePubName());
            // 封装并保存订单明细
            payment = new Payment();
            payment.setUserId(orders.getUserId());// 用户id
            payment.setCompanyId(orders.getCompanyId()); // 课程机构id
            payment.setOrderNo(orderNo);// 订单号
            payment.setStatus("0"); // 交易状态：未支付
            payment.setPayMethod(OrdersConstants.PAY_METHOD_WX); // 支付方式
            payment.setTotalAmount(orders.getPrice());// 订单金额
            payment.setCreateDate(new Date()); // 创建时间
            payment.setPayResponse(payUrl);// 支付连接
            this.save(payment);
            // 返回支付链接
            return ResponseResult.okResult(payUrl);
        }

    }
}